@ loadP.S: Kernel startup routine
@

	.file	"loadP.S"
	.text

	.global	loadP
	.global exit_to_kernel
	
loadP:
   		
	@ Save the Kernel registers on the stack
	STMFD	sp!, {r1-r12, lr}
			
	@ Save the sp of kernel
	LDR	r2, =kernel_sp
	STR	sp, [r2]

	@ Change to the user mode
	MSR	CPSR, #0xD0

	@ Direct sp to 0xA0000000
	LDR	sp, =0xA3000000
	
	@Push a null value
	MOV	r5, #0
	STMFD   sp!, {r5}
	CMP	r0,	#0
	BEQ	launch
	
	@ Save the original argc in r4
	@ (Using argc as a counter)
	MOV	r4,	r0

stack_setup:
	@ Store all argc and argv on the stack
	SUBS	r0,	r0,	#1
	ADD	r2,	r1,	r0,	ASL #2
	LDR	r3,	[r2]
	STMFD	sp!, {r3}
	BNE	stack_setup
	STMFD	sp!, {r4}
	
launch:
	@ Jump to the user program
	LDR	pc,	=0xA0000000

exit_to_kernel:
	@ Restore the original kernel sp
	LDR r2, =kernel_sp
	LDR	sp,	[r2]
	@ Restore the original kernel registers
	@ and exit to kernel
	LDMFD	sp!, {r1-r12, lr}	
	MOV pc, lr
